package com.lcq.demo.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;


/**
 * @author 240701005
 */
public class JWTUtils {

    /**
     * 生成token  header.payload.signature
     */
    private static final String SECRET_KEY = "lcq123456";


    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认10000天过期
        instance.add(Calendar.DATE, 10000);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        map.forEach(builder::withClaim);

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 验证token  合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
    }

    /**
     * 获取token信息方法
     */
    /*public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }*/
    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJleHAiOjE3MjE5NTkyMzMsImVtYWlsIjoiODUwODY2ODUyQHFxLmNvbSJ9.n6E-27iYYBwVPAd4qAmrj3chacM4DFD2NTrZHOcO99s";
        DecodedJWT verify = verify(token);
        System.out.println(verify.getSignature());
        System.out.println(verify.getPayload());
        System.out.println(verify.getHeader());
    }
}
